import random

from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from redis import StrictRedis
from rest_framework.response import Response

from rest_framework.views import APIView

from meiduo_mall.libs.yuntongxun.sms import CCP
from meiduo_mall.utils.exceptions import logger


class SmsCodeView(APIView):
    def get(self, request, mobile, send_sms_code=None):
        strict_redis = get_redis_connection('sms_codes')  # type: StrictRedis

        send_flag = strict_redis.get('send_flag_%s' % mobile)
        if send_flag:
            return Response({'message': '发送短信频繁'}, status=400)
        # raise ValidationError({'message': '发送短信频繁'})

        sms_code = '%06d' % random.randint(0, 999999)
        logger.info('sms_code: %s' % sms_code)

        # CCP().send_template_sms(mobile, [sms_code, 5], 1)

        # 使用celery来发送短信, 可以解决阻塞问题
        # send_sms_code.delay('18813325848', '123456')

        # 保存短信验证码到Redis expiry
        # 1
        # strict_redis.setex('sms_%s' % mobile, 300, sms_code)
        # strict_redis.setex('send_flag_%s' % mobile, 60, 1)
        # 2 优化代码
        pipeline = strict_redis.pipeline()
        pipeline.setex('sms_%s' % mobile, 60 * 5, sms_code)
        pipeline.setex('sms_flag_%s' % mobile, 60, True)
        result = pipeline.execute()
        print(result)

        return Response({'message': 'ok!!!!'})

